package com.xindaoapp.happypet.ui;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.InteralBanner;
import com.xindaoapp.happypet.bean.InteralList;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.view.HomeGroupPager;
import com.xindaoapp.happypet.view.RollViewPager3;


/**
 * 尾巴商城
 * 
 * @author Administrator
 * 
 */
public class ChangeCenterActivity extends BaseActivity {


    private PullToRefreshListView mPullToRefreshListView;
    private ScheduledExecutorService scheduledExecutor;
    private TextView mTitle;
    private ImageView mBackView;
    private TextView vMoreNiu;
    private ListView mlistview;
    /** 轮播图 */
    private LinearLayout mViewPager;
    private TextView mtvDescription;
    private LinearLayout mllPoints;

    private LinearLayout vViewpage;
    private TextView vDescription;

    private List<InteralBanner> mBanners;

    private final boolean isRunning = false;
    private int lastPointIndex = 0;
    private int currentItem;

    private ArrayList<View> dotLists;
    private RollViewPager3 rollViewPager;
    private View viewpager;
    private HomeGroupPager vp;
    private View vChangeViewPager;
    private TextView vNiuniu;
    private ImageView mRmb;


    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {

            // 指定当前页面
            vp.setCurrentItem(currentItem);
        };
    };


    @Override
    protected int getContentViewResId() {
        return R.layout.fragment_change_center;
    }

    @Override
    protected void initViews() {
        super.initViews();
        setTopBarTitle("尾巴币兑换");
        vMoreNiu = (TextView) findViewById(R.id.moreniuniu);
        vNiuniu = (TextView) findViewById(R.id.niuniubi);
        mRmb = (ImageView) findViewById(R.id.rmb);
        // mlistview = (ListView) findViewById(R.id.changelist);
        mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.changelist);
        mPullToRefreshListView.setMode(Mode.PULL_FROM_START);
        mPullToRefreshListView.setOnRefreshListener(mOnRefreshListener);

        // mlistview.setMode(PullToRefreshBase.Mode.BOTH);
        LayoutInflater inflater =
                (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        viewpager = inflater.inflate(R.layout.layout_change_item, null);
        vViewpage = (LinearLayout) viewpager.findViewById(R.id.top_change_viewpager);
        vDescription = (TextView) viewpager.findViewById(R.id.top_change_title);
        // mllPoints = (LinearLayout) viewpager.findViewById(R.id.dots_ll);


        vChangeViewPager = inflater.inflate(R.layout.change_viewpage, null);
        vp = (HomeGroupPager) vChangeViewPager.findViewById(R.id.viewpager);
        scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutor.scheduleAtFixedRate(new MyPagerTask(), 2, 3, TimeUnit.SECONDS);
        mllPoints = (LinearLayout) vChangeViewPager.findViewById(R.id.ll_points1);

        // 隐掉banner
        // mPullToRefreshListView.getRefreshableView().addHeaderView(vChangeViewPager);
    }

    private void isUserLogin() {
        if (UserState.isLogged(ChangeCenterActivity.this)) {
            String niuniu_text = getResources().getString(R.string.weibatext);
            vNiuniu.setText(String.format(niuniu_text, UserState.getUser().niuniu));
            vMoreNiu.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    if (UserState.isLogged(ChangeCenterActivity.this)) {
                        // Intent intent = new Intent(ChangeCenterActivity.this,
                        // MainActivity.class);
                        // intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                        // IntegralFragment.class.getCanonicalName());
                        // ChangeCenterActivity.this.startActivity(intent);
                        // startFragment(new IntegralFragment());
                        Intent intent2 =
                                new Intent(ChangeCenterActivity.this, MyRecordActivity.class);
                        ChangeCenterActivity.this.startActivity(intent2);
                    }
                }
            });
        }
        // else {
        // mRmb.setVisibility(View.INVISIBLE);
        // vNiuniu.setVisibility(View.INVISIBLE);
        // vMoreNiu.setText("登录");
        // vMoreNiu.setOnClickListener(new OnClickListener() {
        //
        // @Override
        // public void onClick(View arg0) {
        // Intent intent = new Intent(ChangeCenterActivity.this, MainActivity.class);
        // intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
        // LoginFragment.class.getCanonicalName());
        // ChangeCenterActivity.this.startActivityForResult(intent,
        // Constants.REQUESTCODE_LOGIN);
        // }
        // });
        // }
    }

    private void initList() {
        getMoccaApi().getChangeList(new IRequest<List<InteralList>>() {

            @Override
            public void request(List<InteralList> t) {
                onDataArrived(true);
                if (t != null) {
                    mPullToRefreshListView.setAdapter(new MyAdapter(t));
                }
                mPullToRefreshListView.onRefreshComplete();
            }

        });
        mPullToRefreshListView.onRefreshComplete();
    }

    @Override
    protected OnClickListener getLeftViewClickListener() {
        return new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        };
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    protected void initEvents() {
        super.initEvents();
    }

    public List<InteralBanner> lists = null;

    private final OnRefreshListener<ListView> mOnRefreshListener =
            new OnRefreshListener<ListView>() {

                @Override
                public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                    onLoadDatas();
                }
            };


    @Override
    protected void onLoadDatas() {
        super.onLoadDatas();
        // getBannerData();
        isUserLogin();
        if (!CommonUtil.checkNetState(getApplicationContext())) {
            HappyPetApplication.mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    onDataArrived(false);
                    mPullToRefreshListView.onRefreshComplete();
                }
            }, 300);
        } else {
            getMoccaApi().getChangePager(new IRequest<List<InteralBanner>>() {

                @Override
                public void request(List<InteralBanner> t) {

                    lists = t;
                    if (lists != null) {
                        // prepareViewPage(list);
                        vp.setAdapter(new MyPagerAdapter(lists));
                        initDots(lists.size());
                    }
                    // mlistview.addHeaderView(viewpager);
                    initList();
                }

            });
        }


        vp.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                currentItem = position;
                int myIndex = position % lists.size();
                // 将当前指示点的图片enable设为true
                mllPoints.getChildAt(myIndex).setEnabled(true);
                // 将上一个指示点设置为false
                mllPoints.getChildAt(lastPointIndex).setEnabled(false);
                lastPointIndex = myIndex;

            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });

    }

    private void initDots(int size) {
        dotLists = new ArrayList<View>();
        mllPoints.removeAllViews();
        for (int i = 0; i < size; i++) {
            // LinearLayout.LayoutParams layoutParams =
            // new LinearLayout.LayoutParams(CommonUtil.dip2px(mActivity, 10),
            // CommonUtil.dip2px(mActivity, 10));
            // layoutParams.setMargins(5, 0, 5, 0);
            // // LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(15,
            // // 15);
            //
            // // lp.leftMargin = 10;
            //
            // View m = new View(mActivity);
            // if (i == 0) {
            // m.setBackgroundResource(R.drawable.point_enable);
            // } else {
            // m.setBackgroundResource(R.drawable.point_normal);
            // }
            // m.setLayoutParams(layoutParams);
            // dotLists.add(m);
            // mllPoints.addView(m);

            // 添加指示点
            ImageView point = new ImageView(getApplicationContext());
            point.setBackgroundResource(R.drawable.point_background);
            LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, -2);
            params.leftMargin = 15;
            point.setLayoutParams(params);

            mllPoints.addView(point);
            if (i == 0) {
                point.setEnabled(true);
            } else {
                point.setEnabled(false);
            }

        }
    }

    class MyAdapter extends BaseAdapter {

        List<InteralList> list;
        int num = 0;

        // List<InteralList> list1;
        // List<InteralList> list2;

        public MyAdapter(List<InteralList> t) {
            super();
            list = t;
            // list1 = t1;
            // list1 = t1;
        }

        @Override
        public int getCount() {
            if (list.size() % 2 == 0) {
                return num = list.size() / 2;
            } else {
                return num = list.size() / 2 + 1;
            }
        }

        @Override
        public Object getItem(int arg0) {
            return null;
        }

        @Override
        public long getItemId(int arg0) {
            return 0;
        }

        @Override
        public boolean isEnabled(int position) {
            return false;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup arg2) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView =
                        View.inflate(getApplicationContext(), R.layout.item_changecenter, null);
                holder.img1 = (ImageView) convertView.findViewById(R.id.img1);
                holder.img2 = (ImageView) convertView.findViewById(R.id.img2);
                holder.title1 = (TextView) convertView.findViewById(R.id.title1);
                holder.jifen1 = (TextView) convertView.findViewById(R.id.jifen1);
                holder.title2 = (TextView) convertView.findViewById(R.id.title2);
                holder.jifen2 = (TextView) convertView.findViewById(R.id.jifen2);
                holder.ll1 = (LinearLayout) convertView.findViewById(R.id.ll1);
                holder.ll2 = (LinearLayout) convertView.findViewById(R.id.ll2);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.img1.setScaleType(ScaleType.FIT_XY);
            holder.img2.setScaleType(ScaleType.FIT_XY);

            android.view.ViewGroup.LayoutParams lp1 = holder.img1.getLayoutParams();
            android.view.ViewGroup.LayoutParams lp2 = holder.img2.getLayoutParams();
            lp1.width =
                    (CommonParameter.sScreenWidth - CommonUtil.dp2px(ChangeCenterActivity.this, 30)) / 2;
            lp1.height =
                    (CommonParameter.sScreenWidth - CommonUtil.dp2px(ChangeCenterActivity.this, 30)) / 2;
            lp2.width =
                    (CommonParameter.sScreenWidth - CommonUtil.dp2px(ChangeCenterActivity.this, 30)) / 2;
            lp2.height =
                    (CommonParameter.sScreenWidth - CommonUtil.dp2px(ChangeCenterActivity.this, 30)) / 2;

            if (num == position + 1 && list.size() % 2 == 1) {
                ImageLoader.getInstance().displayImage(list.get(position * 2).goods_thumb,
                        holder.img1);
                holder.ll1.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // Intent intent = new Intent(ChangeCenterActivity.this,
                        // MainActivity.class);
                        // intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                        // ChangeDescFragment.class.getCanonicalName());
                        // ChangeCenterActivity.this.startActivity(intent);
                        // startFragment(new ChangeDescFragment(), bundle);
                        Intent intent =
                                new Intent(ChangeCenterActivity.this, ChangeDescActivity.class);
                        intent.putExtra("ex_id", list.get(position * 2).ex_id + "");
                        startActivityForResult(intent, 0);
                    }
                });
            } else {
                ImageLoader.getInstance().displayImage(list.get(position * 2).goods_thumb,
                        holder.img1);
                holder.title1.setText(list.get(position * 2).goods_name);
                holder.jifen1.setText(list.get(position * 2).exchange_integral + "尾巴币");
                ImageLoader.getInstance().displayImage(list.get((position * 2) + 1).goods_thumb,
                        holder.img2);
                holder.title2.setText(list.get((position * 2) + 1).goods_name);
                holder.jifen2.setText(list.get((position * 2) + 1).exchange_integral + "尾巴币");
                holder.ll1.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // Intent intent = new Intent(ChangeCenterActivity.this,
                        // MainActivity.class);
                        // intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                        // ChangeDescFragment.class.getCanonicalName());
                        // Bundle bundle = new Bundle();
                        // bundle.putString("ex_id", list.get(position * 2).ex_id + "");
                        // intent.putExtra(Constants.KEY_BUNDLE, bundle);
                        // ChangeCenterActivity.this.startActivity(intent);
                        // startFragment(new ChangeDescFragment(), bundle);
                        Intent intent =
                                new Intent(ChangeCenterActivity.this, ChangeDescActivity.class);
                        intent.putExtra("ex_id", list.get(position * 2).ex_id + "");
                        startActivityForResult(intent, 0);
                    }
                });
                holder.ll2.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // Intent intent = new Intent(ChangeCenterActivity.this,
                        // MainActivity.class);
                        // intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                        // ChangeDescFragment.class.getCanonicalName());
                        // Bundle bundle = new Bundle();
                        // bundle.putString("ex_id", list.get((position * 2) + 1).ex_id + "");
                        // intent.putExtra(Constants.KEY_BUNDLE, bundle);
                        // ChangeCenterActivity.this.startActivity(intent);
                        // startFragment(new ChangeDescFragment(), bundle);
                        Intent intent =
                                new Intent(ChangeCenterActivity.this, ChangeDescActivity.class);
                        intent.putExtra("ex_id", list.get((position * 2) + 1).ex_id + "");
                        startActivityForResult(intent, 0);
                    }
                });
            }



            // img1.setImageResource();
            // img2.setImageResource(R.drawable.all292);
            return convertView;
        }
    }

    class ViewHolder {
        private LinearLayout ll1;
        private LinearLayout ll2;
        private ImageView img1;
        private ImageView img2;
        private TextView title1;
        private TextView jifen1;
        private TextView title2;
        private TextView jifen2;
    }


    private class MyPagerAdapter extends PagerAdapter {

        List<InteralBanner> list;

        public MyPagerAdapter(List<InteralBanner> list) {
            super();
            this.list = list;
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // 获得指定位置的view
            ImageView iv = new ImageView(getApplicationContext());
            iv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.MATCH_PARENT));
            iv.setScaleType(ScaleType.FIT_XY);
            ImageLoader.getInstance().displayImage(list.get(position % list.size()).coverpath, iv);
            // 将view 添加至container
            container.addView(iv);
            return iv;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

    }

    private class MyPagerTask implements Runnable {

        @Override
        public void run() {
            // 切换图片
            currentItem = currentItem + 1;
            handler.sendEmptyMessage(0);
        }
    }

    @Override
    protected int getTopBarLeftImageViewRes() {
        return R.drawable.top_bar_back;
    }

    @Override
    public void onResume() {
        super.onResume();
        // onLoadData();
        isUserLogin();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1) {
            finish();
        }
    }

}
